package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Spot;
import cn.wolfcode.wolf2w.query.SpotQuery;
import cn.wolfcode.wolf2w.repository.SpotRepository;
import cn.wolfcode.wolf2w.service.ISpotService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
//@Transactional mongodb事务必须是复制集方式
public class SpotServiceImpl implements ISpotService {


    @Autowired
    private SpotRepository repository;


    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Spot spot) {
        repository.save(spot);
    }

    @Override
    public void update(Spot spot) {
        repository.save(spot);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Spot get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {
        return repository.findAll();
    }

    @Override
    public Page<Spot> query(SpotQuery qo) {
        //查询对象
        Query query = new Query();

        Long total = template.count(query, Spot.class);
        if(total == 0){
            return Page.empty();//空的分页对象
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"_id");
        return DBHelper.query(template,Spot.class,query,pageable);
    }



}
